using Godot;
using System;

public partial class NCharacter : CharacterBody2D
{
	[Export] public CCharacterData mData;

	AnimatedSprite2D mAni;
	CollisionShape2D mShape;
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		mAni = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
		mShape = GetNode<CollisionShape2D>("CollisionShape2D");

		CHelp.addToGroup(this, mData.mChaType.ToString());

		if (mData == null)
			mData = new CCharacterData();

		mData = mData.copy();
		
	}

	public void beAttack(NCharacter emeny)
	{
		if (mData.mState is CIdleState)
		{
			mData.mSkillTarget.mID = SKILL_ID.SKILL_PYHSICS;
			mData.mSkillTarget.mTargetPath = CHelp.getNearestEnemy(this, 1000).GetPath().ToString();
			mData.mState = new CPreSkillState();
		}
	}

	public AnimatedSprite2D Ani
	{
		get { return mAni; }
	}

	public float ColShapeDis
	{
		get
		{
			if (mShape.Shape is CircleShape2D cs)
			{
				return cs.Radius;
			}
			return 0;
		}
	}

	public CSkill CurSkill
	{
		get
		{
			return getSkill(mData.mSkillTarget.mID);
		}
	}

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		mData.mState.run(this, delta);
	}

	public override void _UnhandledInput(InputEvent @event)
	{
		if (@event is InputEventMouseButton mb)
		{
			if (mb.Pressed && mb.ButtonIndex == MouseButton.Right)
			{
				if (mData.mChaType == CHA_TYPE.FRIEND)
				{
					mData.mMoveTarget = GetGlobalMousePosition();
					mData.mState = new CMoveState();
				}
			}
		}
	}

	public CSkill getSkill(SKILL_ID id)
	{
		foreach (var v in mData.mSkills)
		{
			if (v.mID == id)
			{
				return v;
			}
		}
		return null;
	}

	public void play(ANI_TYPE at)
	{
		_play(at, mData.mDir);
	}
	void _play(ANI_TYPE at, DIR d)
	{
		string aniName = string.Format("{0}_{1}", at.ToString().ToLower(), d.ToString().ToLower());

		mAni.Play(aniName);
	}
	public string aniName(ANI_TYPE at)
	{
		return string.Format("{0}_{1}", at.ToString().ToLower(), mData.mDir.ToString().ToLower());

	}
}
